<template>
  <div class="modal-wrapper" v-loading="loading">
    <div style="margin-bottom: 32px">
      <modelResults :dataList="modelResults"></modelResults>
    </div>
    <div class="form-btn-row is-right">
      <mine-button type="primary" @click="cancel" secondary>取 消</mine-button>
      <mine-button
        type="primary"
        @click="save"
        v-loading.fullscreen.lock="fullscreenLoading"
        >发布模型</mine-button
      >
    </div>
  </div>
</template>
<script>
import modelResults from "../addModel/modelResults";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
import { forIn } from "lodash";
export default {
  components: {
    modelResults,
  },
  props: {
    modelId: [String, Number],
    projectId: [String, Number],
    fullscreenLoading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      modelResults: [],
      modelData: {},
      loading: false,
    };
  },
  methods: {
    async show() {
      this.loading = true;
      let taskId = "";
      try {
        let task = await this.loadTask();
        console.log(task);
        if (task) {
          taskId = task.id;
        }
      } catch (e) {
        console.error(e);
      }
      let modelData = {};
      try {
        modelData = await this.getModelData(taskId);
      } catch (err) {
        console.error(err);
      }
      this.loading = false;

      let evaluate = eval("(" + modelData.evaluate + ")"),
        result = [];
      evaluate = forIn(evaluate, (value, key) => {
        let obj = {
          name: key,
          ...value,
        };
        result.push(obj);
      });
      this.modelData = modelData;
      this.modelResults = result;
    },
    async loadTask() {
      const params = {
        projectId: this.projectId || "",
      };
      // let value;
      this.loading = true;
      let res = {};
      let _self = this;
      return new Promise(async (resolve, reject) => {
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/traininginfo/training-info/getByProjectId?projectId=${params.projectId}`,
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {},
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                const data = result.data;
                // value = data;
                resolve(data);
              } else {
                _self.$message.error("获取失败！");
              }
            });
          }
        } else if (_self.$webview2.isWPF) {
          const uuid = _self.$webview2.generateRandomUUID();
          await _self.$webview2.sendWebView2(
            `/traininginfo/training-info/getByProjectId?projectId=${params.projectId}`,
            "get",
            "application/json;charset=UTF-8",
            {},
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              console.log(res);
              // TODO： 定制后台数据处理
              if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                const data = res.data;
                // value = data;
                resolve(data);
              } else {
                _self.$message.error("获取失败！");
              }
            },
            { once: true }
          );
        } else {
          const res = await _self.$store.dispatch(
            "modelManageTraininginfoTrainingInfoGetByProjectId",
            params
          );
          const result = res.data || {};
          if (result.success) {
            const data = result.data;
            // value = data;
            resolve(data);
          } else {
            _self.$message.error("获取失败！");
          }
        }
        _self.loading = false;
        // return value;
      });
    },
    async getModelData(taskId) {
      const params = {
        taskId: taskId,
      };
      let res = {};
      let _self = this;
      return new Promise(async (resolve, reject) => {
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/training-model-data/find-by-training-task/${params.taskId}`,
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {},
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                const data = result.data;
                // value = data;
                resolve(data);
              } else {
                _self.$message.error("获取失败！");
              }
            });
          }
        } else if (_self.$webview2.isWPF) {
          const uuid = _self.$webview2.generateRandomUUID();
          await _self.$webview2.sendWebView2(
            `/training-model-data/find-by-training-task/${params.taskId}`,
            "get",
            "application/json;charset=UTF-8",
            {},
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                const data = res.data;
                // value = data;
                resolve(data);
              } else {
                _self.$message.error("获取失败！");
              }
            },
            { once: true }
          );
        } else {
          const res = await _self.$store.dispatch(
            "modelManageTrainingModelDataFindByTrainingTask",
            params
          );
          const result = res.data || {};
          if (result.success) {
            // value = result.data || {};
            resolve(result.data);
          } else {
            _self.$message.error("获取失败！");
          }
        }
      });
      // return value;
    },
    async save() {
      const params = {
        modelId: this.modelData.id,
      };
      this.loading = true;
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/publishtask/publish-task-data/publish`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: params,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.$message.success("发布成功");
              _self.$emit("close");
              _self.$emit("callback");
            } else {
              _self.$message.error("发布失败！:" + result.msg);
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/publishtask/publish-task-data/publish`,
          "post",
          "application/json;charset=UTF-8",
          params,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.$message.success("发布成功");
              this.$emit("close");
              this.$emit("callback");
            } else {
              this.$message.error("发布失败！:" + res.msg);
            }
            this.loading = false;
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch(
          "modelManagePublishtaskPublishTaskDataPublish",
          params
        );
        const result = res.data || {};
        if (result.success) {
          this.$message.success("发布成功");
          this.$emit("close");
          this.$emit("callback");
        } else {
          this.$message.error("发布失败！:" + result.msg);
        }
        this.loading = false;
      }
    },
    cancel() {
      this.$emit("close");
    },
  },
};
</script>
